<template>
  <div class="article-page">
    <a-card :bordered="false">
      <template #title>
        <div class="card-title">
          <span>文章管理</span>
        </div>
      </template>
      <template #extra>
        <a-button type="primary" @click="handleAdd">
          <template #icon>
            <PlusOutlined />
          </template>
          发布文章
        </a-button>
      </template>

      <a-form layout="inline" :model="searchForm" class="search-form">
        <a-form-item label="文章标题">
          <a-input
            v-model:value="searchForm.title"
            placeholder="请输入文章标题"
            style="width: 200px"
            @press-enter="handleSearch"
          />
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="handleSearch">
            <template #icon>
              <SearchOutlined />
            </template>
            搜索
          </a-button>
          <a-button style="margin-left: 8px" @click="handleReset">重置</a-button>
        </a-form-item>
      </a-form>

      <a-table
        :columns="columns"
        :data-source="dataSource"
        :loading="loading"
        :pagination="pagination"
        @change="handleTableChange"
        row-key="id"
        class="article-table"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'article_cover'">
            <a-image
              v-if="record.article_cover"
              :src="record.article_cover"
              :width="60"
              :height="60"
              :preview="true"
              style="object-fit: cover; border-radius: 4px"
            />
            <span v-else class="no-cover">暂无封面</span>
          </template>
          <template v-if="column.key === 'category_id'">
            <a-tag v-for="tag in record.categoryId.split(',')" :key="tag" color="blue">
              {{ renderTag(tag) }}
            </a-tag>
          </template>
          <template v-if="column.key === 'content'">
            <div class="content-preview">
              {{ getContentPreview(record.content) }}
            </div>
          </template>
          <template v-if="column.key === 'action'">
            <a-space>
              <a-button type="link" size="small" @click="handleEdit(record as any)">
                <EditOutlined />
                编辑
              </a-button>
              <a-popconfirm
                title="确定要删除这篇文章吗？"
                ok-text="确定"
                cancel-text="取消"
                @confirm="handleDelete(record as any)"
              >
                <a-button type="link" size="small" danger>
                  <DeleteOutlined />
                  删除
                </a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 发布/编辑文章弹窗 -->
    <ArticleEditor
      v-model:visible="editorVisible"
      @success="handleEditorSuccess"
      :articleId="articleId"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { PlusOutlined, SearchOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons-vue'
import ArticleEditor from './components/ArticleEditor.vue'
import { getArticles, getArticleTags, deleteArticle } from '@/api/article'
interface Article {
  id: number
  title: string
  content: string
  category_id: string[]
  article_cover: string
  created_at?: string
}

const searchForm = reactive({
  title: '',
})
const tags = ref<string[]>([])
const loading = ref(false)
const editorVisible = ref(false)
const articleId = ref<number | null>(null)
// 渲染标签的函数
const renderTag = (tagId: string) => {
  console.log(tagId)
  console.log(tags.value)
  return tags.value.find((t: any) => +t.id === +tagId)?.name || tagId
}
const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    key: 'id',
    width: 80,
  },
  {
    title: '封面',
    dataIndex: 'article_cover',
    key: 'article_cover',
    width: 100,
  },
  {
    title: '文章标题',
    dataIndex: 'title',
    key: 'title',
    width: 300,
    ellipsis: true,
  },
  {
    title: '内容预览',
    dataIndex: 'content',
    key: 'content',
    ellipsis: true,
  },
  {
    title: '标签',
    dataIndex: 'category_id',
    key: 'category_id',
    width: 230,
  },
  {
    title: '创建时间',
    dataIndex: 'created_at',
    key: 'created_at',
    width: 180,
  },
  {
    title: '操作',
    key: 'action',
    width: 150,
    fixed: 'right' as const,
  },
]

const dataSource = ref<Article[]>([])

const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showTotal: (total: number) => `共 ${total} 条`,
})
// 获取标签列表
const getTagList = async () => {
  try {
    const res = await getArticleTags()
    if (res.code === 200) {
      tags.value = res.data
    }
    console.log(res)
  } catch (error) {
    message.error('获取标签列表失败')
  }
}
// 获取文章列表
const getArticleList = async () => {
  loading.value = true
  try {
    // TODO: 调用实际 API
    const res = await getArticles({
      page: pagination.current,
      size: pagination.pageSize,
      title: searchForm.title,
    })
    if (res.code === 200) {
      dataSource.value = res.data.list
      pagination.total = res.data.total
    }
    console.log(res)
  } catch (error) {
    message.error('获取文章列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  getArticleList()
}

// 重置
const handleReset = () => {
  searchForm.title = ''
  pagination.current = 1
  getArticleList()
}

// 新增文章
const handleAdd = () => {
  articleId.value = null
  editorVisible.value = true
}

// 编辑文章
const handleEdit = (record: any) => {
  articleId.value = record.id
  editorVisible.value = true
}

// 删除文章
const handleDelete = async (record: any) => {
  try {
    // TODO: 调用实际 API
    const res: any = await deleteArticle(record.id)
    if (res.code !== 200) {
      throw new Error(res.message || '删除失败')
    } else {
      message.success('删除成功')
      getArticleList()
    }
  } catch (error) {
    message.error('删除失败')
  }
}

// 表格分页变化
const handleTableChange = (pag: any) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
  getArticleList()
}

// 编辑器成功回调
const handleEditorSuccess = () => {
  editorVisible.value = false
  getArticleList()
}

// 获取内容预览
const getContentPreview = (content: string) => {
  if (!content) return '暂无内容'
  // 移除 Markdown 标记，获取纯文本
  const plainText = content.replace(/[#*`[\]()]/g, '').trim()
  return plainText.length > 50 ? plainText.substring(0, 50) + '...' : plainText
}

onMounted(() => {
  getTagList()
  getArticleList()
})
</script>

<style scoped>
.article-page {
  width: 100%;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
}

.search-form {
  margin-bottom: 16px;
}

.article-table :deep(.ant-table) {
  font-size: 14px;
}

.article-table :deep(.ant-table-thead > tr > th) {
  background: #fafafa;
  font-weight: 600;
}

.no-cover {
  color: #999;
  font-size: 12px;
}

.content-preview {
  color: #666;
  font-size: 13px;
  line-height: 1.5;
}
</style>
